package org.kyw.order.service.impl;

import org.kyw.basic.service.impl.BaseServiceImpl;
import org.kyw.basic.util.CodeGenerateUtils;
import org.kyw.basic.util.PageList;
import org.kyw.order.domain.AdoptOrder;
import org.kyw.order.domain.OrderAddress;
import org.kyw.order.mapper.AdoptOrderMapper;
import org.kyw.order.mapper.OrderAddressMapper;
import org.kyw.order.query.AdoptOrderQuery;
import org.kyw.order.service.IAdoptOrderService;
import org.kyw.org.domain.Employee;
import org.kyw.org.mapper.EmployeeMapper;
import org.kyw.pay.constants.PayConstants;
import org.kyw.pay.domain.PayBill;
import org.kyw.pay.mapper.PayBillMapper;
import org.kyw.pay.service.IAlipayInfoService;
import org.kyw.pet.domain.Pet;
import org.kyw.pet.mapper.PetMapper;
import org.kyw.quartz.constant.JobTypeConstants;
import org.kyw.quartz.service.IQuartzService;
import org.kyw.quartz.util.QuartzJobInfo;
import org.kyw.user.domain.Logininfo;
import org.kyw.user.domain.User;
import org.kyw.user.domain.UserAddress;
import org.kyw.user.mapper.UserAddressMapper;
import org.kyw.user.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdoptOrderServiceImpl extends BaseServiceImpl<AdoptOrder> implements IAdoptOrderService {
    @Autowired
    private PetMapper petMapper;
    @Autowired
    private AdoptOrderMapper adoptOrderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserAddressMapper userAddressMapper;
    @Autowired
    private OrderAddressMapper orderAddressMapper;

    @Value("${order.pay.time.last}")
    private Integer lastPayTime;

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private PayBillMapper payBillMapper;
    @Autowired
    private IAlipayInfoService alipayInfoService;
    @Autowired
    private IQuartzService quartzService;

    @Override
    public String submit(Map<String, Object> params, Logininfo currentLogin) {
        Integer serviceMethod = Integer.valueOf(params.get("service_method").toString());
        Long addressId = Long.valueOf(params.get("address_id").toString());
        Long payMethod = Long.valueOf(params.get("pay_method").toString());
        Long petId = Long.valueOf(params.get("pet_id").toString());
        //宠物下架 + 下架时间
        Pet pet = petMapper.loadById(petId);
        pet.setState(0);
        pet.setOffsaletime(new Date());
        petMapper.update(pet);

        //生成领养订单
        User user = userMapper.loadByLogininfoId(currentLogin.getId());
        AdoptOrder order = initAdoptOrder(pet, user);
        order.setPaySn(CodeGenerateUtils.generateUnionPaySn());
        adoptOrderMapper.save(order);

        //订单的收货地址
        UserAddress userAddress = userAddressMapper.loadById(addressId);
        OrderAddress orderAddress = initOrderAddress(order, userAddress);
        orderAddressMapper.save(orderAddress);

        //支付
        PayBill bill = initPayBill(payMethod, user, order);
        payBillMapper.save(bill);

        QuartzJobInfo quartzJobInfo = new QuartzJobInfo();
        String jobName = JobTypeConstants.TIME_OUT_ADOPT_LAST_PAY + order.getId();
        quartzJobInfo.setJobName(jobName);
        Map<String,Object> map = new HashMap<>();
        map.put("type", JobTypeConstants.TIME_OUT_ADOPT_LAST_PAY);
        map.put("orderId", order.getId());
        quartzJobInfo.setParams(map);
        quartzJobInfo.setFireDate(order.getLastPayTime());
        quartzService.addJob(quartzJobInfo);

        switch (payMethod.intValue()){
            case 0:{
                break;
            }
            case 1:{
                return alipayInfoService.pay(bill);
            }
            case 2:break;
            case 3:break;
            default:break;
        }
        return null;
    }

    private PayBill initPayBill(Long payMethod, User user, AdoptOrder order) {
        PayBill bill = new PayBill();
        bill.setDigest(order.getDigest());
        bill.setMoney(order.getPrice());
        bill.setUnionPaySn(order.getPaySn());
        bill.setLastPayTime(order.getLastPayTime());
        bill.setPayChannel(payMethod);
        bill.setBusinessType(PayConstants.BUSINESS_TYPE_ADOPT_ORDER);
        bill.setBusinessKey(order.getId());
        bill.setUser_id(user.getId());
        bill.setShop_id(order.getShop_id());
        bill.setNickName(user.getUsername());
        return bill;
    }

    @Override
    public PageList<AdoptOrder> queryUserOrder(AdoptOrderQuery query, Logininfo currentLogin) {
        User user = userMapper.loadByLogininfoId(currentLogin.getId());
        query.setUserId(user.getId());
        return super.queryPage(query);
    }

    @Override
    public PageList<AdoptOrder> queryAdmin(AdoptOrderQuery query, Logininfo currentLogin) {
        Employee employee = employeeMapper.loadByLogininfoId(currentLogin.getId());
        if(employee != null){
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }

    @Override
    public void cancelByQuartz(Long orderId) {
        AdoptOrder adoptOrder = adoptOrderMapper.loadById(orderId);
        if(adoptOrder != null) {
            if(adoptOrder.getState() == 0) {
                adoptOrder.setState(-1);
                adoptOrderMapper.update(adoptOrder);
            }
        }
    }

    private OrderAddress initOrderAddress(AdoptOrder order, UserAddress userAddress) {
        OrderAddress orderAddress = new OrderAddress();
        BeanUtils.copyProperties(userAddress, orderAddress);
        orderAddress.setOrder_id(order.getId());
        orderAddress.setOrderSn(order.getOrderSn());
        return orderAddress;
    }

    private AdoptOrder initAdoptOrder(Pet pet, User user) {
        AdoptOrder order = new AdoptOrder();
        order.setDigest("[摘要]对"+pet.getName()+"领养订单！");
        order.setState(0);//待支付
        order.setPrice(pet.getSaleprice());
        String orderSn = CodeGenerateUtils.generateOrderSn(user.getId());
        order.setOrderSn(orderSn);
        order.setPet_id(pet.getId());
        order.setUser_id(user.getId());
        order.setShop_id(pet.getShop_id());
        order.setLastPayTime(new Date(System.currentTimeMillis() + lastPayTime));
        return order;
    }
}
